package handler

import (
	"ecommerce-customer-support-chat/api/request"
	"ecommerce-customer-support-chat/consts"
	"ecommerce-customer-support-chat/internal/dao"
	"ecommerce-customer-support-chat/internal/model"
	"ecommerce-customer-support-chat/pkg"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	jwt2 "github.com/golangblogs/gojwt"
	"net/http"
	"time"
)

func CreateUser(c *gin.Context) {
	var req request.CreateUserReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "查询失败",
			"data": err.Error(),
		})
		return
	}
	var user model.Users
	dao.GetOneByFields(&model.Users{Email: req.Email}, &user)
	if user.Id != 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10001,
			"msg":  "用户已存在",
			"data": nil,
		})
		return
	}
	users := model.Users{
		Email:    req.Email,
		Password: pkg.Md5(req.Password),
	}
	if !dao.Create(&users) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10002,
			"msg":  "注册失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "注册成功",
		"data": users.Email,
	})
}

func LoginUser(c *gin.Context) {
	var req request.LoginUserReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "查询失败",
			"data": err.Error(),
		})
		return
	}
	var user model.Users
	dao.GetOneByFields(&model.Users{Email: req.Email}, &user)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10001,
			"msg":  "账号未注册",
			"data": nil,
		})
		return
	}
	if user.Password != pkg.Md5(req.Password) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10002,
			"msg":  "密码错误",
			"data": nil,
		})
		return
	}
	token, err := jwt2.NewJWT(consts.JWT_SELECT_KEY).CreateToken(jwt2.CustomClaims{
		ID: uint(user.Id),
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + 86400,
		},
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10003,
			"msg":  "jwt异常",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登陆成功",
		"data": token,
	})
}
